package com.tarena.lbs.coupon.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.coupon.dao.mapper.StockMapper;
import com.tarena.lbs.coupon.dao.repository.StockRepository;
import com.tarena.lbs.coupon.pojo.po.CouponStockPO;
import com.tarena.lbs.coupon.pojo.query.CouponStockParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Date;

@Repository
public class StockRepositoryImpl implements StockRepository {
    @Autowired
    private StockMapper stockMapper;
    @Override
    public void Insert(CouponStockPO couponStockPO){
        stockMapper.insert(couponStockPO);
    }

    @Override
    public Boolean addStock(CouponStockParam param) throws BusinessException {
        //封装一下PO，写入数据库。如果考虑幂等，一个couponId只能存在一个stock库存数据
        //先查再增，外部包裹一个锁
        Long count=stockMapper.selectCount(new QueryWrapper<CouponStockPO>().eq("coupon_id",param.getCouponId()));
        Asserts.isTrue(count>0,new BusinessException("-2","库存已存在"));
        //没有库存，组织一个po写入数据库
        CouponStockPO couponStockPO = new CouponStockPO();
        BeanUtils.copyProperties(param, couponStockPO);
        couponStockPO.setCreateAt(new Date());
        int result =stockMapper.insert(couponStockPO);
        return result>0;
    }

    @Override
    public CouponStockPO selectById(Integer id) {
       return stockMapper.selectById(id);

    }

    @Override
    public int delStock(Integer couponId) {
       int num= stockMapper.deleteById(couponId);
        return num;
    }


}
